use std::time::Duration;

use salvo::{prelude::{Logger, OpenApi, SwaggerUi}, Router};
use salvo::cache::{Cache, MokaStore, RequestIssuer};
use salvo::proxy::Proxy;
use crate::config::CFG;
use crate::middleware::cors::cors_middleware;
use crate::routers::demo::{get_group_package_tgz, get_package, get_package_tgz, get_package_version, hoop_test, set_data};

pub mod demo;
mod static_routers;

pub fn router() -> Router {
    let _cors_handler = cors_middleware();
    let mut static_routers = static_routers::create_static_routers();
    let router = Router::new()
        .hoop(_cors_handler)
        .hoop(Logger::new())
        .append(&mut static_routers);
    let doc = OpenApi::new("salvo web api", "0.0.1").merge_router(&router);
    router
        .push(doc.into_router("/api-doc/openapi.json"))
        .push(SwaggerUi::new("/api-doc/openapi.json").into_router("swagger-ui"))
        .hoop(set_data)
        // 缓存
        .hoop(
            Cache::new(
                MokaStore::builder()
                    .time_to_live(Duration::from_secs(30))
                    .max_capacity(500)
                    .time_to_idle(Duration::from_secs(5))
                    .initial_capacity(500)
                    .build(),
                RequestIssuer::default()
                    .use_authority(false)
                    .use_query(false)
            ))
        .push(
            Router::with_path("<package>")
                .get(get_package)
                .push(
                    Router::with_path("<version>").get(get_package_version)
                )
                .push(
                    Router::with_path("/-/<package_tgz>").get(get_package_tgz)
                )
        )
        .push(
            Router::with_path("/<group>/<package>/-/<package_tgz>")
                .get(get_group_package_tgz)
        )
        .push(
            Router::with_path("<**>")
                .hoop(hoop_test)
                .goal(Proxy::default_hyper_client(
                    if !CFG.server.registry.is_empty() {
                        CFG.server.registry.clone()
                    } else {
                        "https://mirrors.huaweicloud.com/repository/npm".to_string()
                    }
                )
                )
        )
}
